package com.prb.tpn.filter.common;


import com.prb.tpn.filter.dto.StatisticalInfo;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TpnRobot implements Runnable {

    private static Map<String, List<StatisticalInfo>> statisticalMap = new ConcurrentHashMap<>();

    public TpnRobot() {

        // 每隔5秒打印线程使用情况
        Executors.newSingleThreadScheduledExecutor()
                .scheduleWithFixedDelay(this, 3, 5, TimeUnit.SECONDS);


        //移除一分钟 以外的统计信息
        Executors.newSingleThreadScheduledExecutor()
                .scheduleWithFixedDelay(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("---删除过期数据---");
                        for (Map.Entry<String , List<StatisticalInfo>> methodInfos : statisticalMap.entrySet()) {
                            List<StatisticalInfo> methodList = methodInfos.getValue();
                            Iterator<StatisticalInfo> iterator = methodList.iterator();
                            Long removeCon = System.currentTimeMillis() - 60000;
                            while (iterator.hasNext()) {
                                StatisticalInfo info = iterator.next();
                                if (info.getInvokeTime() < removeCon) {
                                    iterator.remove();
                                }
                            }
                        }
                    }
                }, 10, 20, TimeUnit.SECONDS);
    }


    public void addStatisticalInfo(String serverName, StatisticalInfo statisticalInfo) {

        List<StatisticalInfo> statisticalInfos = statisticalMap.computeIfAbsent(serverName, key -> new ArrayList<>());
        statisticalInfos.add(statisticalInfo);

    }


    @Override
    public void run() {

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String dateStr = sdf.format(date);
        if(statisticalMap.isEmpty()){
            System.out.println("统计信息为空");
        }else{
            for (Map.Entry<String, List<StatisticalInfo>> methodInfos : statisticalMap.entrySet()) {
                System.out.println(dateStr + methodInfos.getKey() + "的TP90:" + getTP(methodInfos.getValue(), 0.9) + "毫秒");
                System.out.println(dateStr + methodInfos.getKey() + "的TP99:" + getTP(methodInfos.getValue(), 0.99) + "毫秒");
            }
        }
    }


    private Long getTP(List<StatisticalInfo> statisticalInfos, double rate) {
        // 构建一个临时数组保存 满足1一分钟之内的数据
        List<StatisticalInfo>  sortInfo = new ArrayList<>();
        // 计算最近一分钟的TP90 和 TP99
        long  endTime = System.currentTimeMillis();
        long  startTime = System.currentTimeMillis() - 60000;
        // 遍历列表集合
        int  length = statisticalInfos.size();
        for (int i=0 ; i < length ; i++){
            //System.out.println("#######");
            StatisticalInfo  statisticalInfo = statisticalInfos.get(i);
            if (statisticalInfo.getInvokeTime() >= startTime && statisticalInfo.getInvokeTime() <= endTime){
                sortInfo.add(statisticalInfo);
            }
        }
        sortInfo.sort(new Comparator<StatisticalInfo>() {
            @Override
            public int compare(StatisticalInfo o1, StatisticalInfo o2) {
                if(o1.getInvokeTime() > o2.getInvokeTime()){
                    return  1;
                }else if(o1.getInvokeTime() < o2.getInvokeTime()){
                    return -1;
                }else{
                    return  0;
                }

            }
        });
        int  index = (int)(sortInfo.size() * rate);

        return sortInfo.get(index).getInvokeTime();
    }
}
